package com.mtiiot.fsmanage.core.dao;

import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import com.mtiiot.fsmanage.bean.common.SysTreeNode;
import com.mtiiot.fsmanage.bean.parameter.Sys;
import com.mtiiot.fsmanage.bean.parameter.User;
import com.mtiiot.fsmanage.utils.Contants;
import com.mtiiot.fsmanage.utils.TimeUtil;
import com.mtiiot.fscore.utils.StringUtil;
import org.codehaus.jackson.map.ObjectMapper;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.health.ClusterIndexHealth;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 16-7-29.
 */
@Repository
public class BaseElasticsearch {
    @Autowired
    private ElasticsearchDataSource esDataSource;
    public ElasticsearchDataSource getEsDataSource() {
        return esDataSource;
    }
    public void setEsDataSource(ElasticsearchDataSource esDataSource) {
        this.esDataSource = esDataSource;
    }

    /**
     * 系统自动产生id 创建1个文档
     * @param index 索引名称
     * @param type  索引type
     * @param sourcecontent 要索引的内容
     */
    public boolean createIndex(String index,String type,String sourcecontent) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            IndexResponse response = client.prepareIndex(index, type).setSource(sourcecontent).execute().actionGet();
            return response.isCreated();
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    /**
     * 自己设置id创建1个文档
     * @param index 索引名称
     * @param type  索引type
     * @param sourcecontent 要索引的内容
     */
    public boolean createIndexById(String index,String type,String sourcecontent,String id) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            IndexResponse response = client.prepareIndex(index, type).setId(id).setSource(sourcecontent).setTimestamp(sdf.format(new Date())).execute().actionGet();
            return response.isCreated();
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    /**
     * 系统自动产生id 批量创建个文档
     * @param index 索引名称
     * @param type  索引type
     * @param sourcecontents 要索引的内容
     */
    public boolean batchCreateIndex(String index,String type,List<String> sourcecontents) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            BulkRequestBuilder bulkRequest=client.prepareBulk();
            for(String sourcecontent:sourcecontents){
                bulkRequest.add(client.prepareIndex(index, type).setSource(sourcecontent));
            }
            BulkResponse bulkResponse=bulkRequest.execute().actionGet();
            boolean result=bulkResponse.hasFailures();
            if(result){
                throw new Exception(bulkResponse.buildFailureMessage());
            }
            return !result;
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    /**
     * 批量修改文档
     * @param index 索引名称
     * @param type  索引type
     * @param map  批量更新map map结构中 3个string分别对应(id,field,value)
     */
    public boolean batchUpdateIndex(String index,String type,Map<String,Map<String,String>> map) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            BulkRequestBuilder bulkRequest=client.prepareBulk();
            Set<String> keys=map.keySet();
            for(String key:keys){
                bulkRequest.add(client.prepareUpdate(index, type,key).setDoc(map.get(key)));
            }
            BulkResponse bulkResponse=bulkRequest.execute().actionGet();
            boolean result=bulkResponse.hasFailures();
            if(result){
                throw new Exception(bulkResponse.buildFailureMessage());
            }
            return !result;
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    /**
     * 根据修改文档
     * @param index 索引名称
     * @param type  索引type
     * @param id  id
     * @param map 要索引的内容
     */
    public boolean updateIndex(String index,String type,String id,Map map) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            UpdateResponse response = client.prepareUpdate(index, type,id).setDoc(map).execute().actionGet();
            return response.isCreated();
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }


    /**
     * 根据id删除文档
     * @param index
     * @param type
     * @param id
     */
    public boolean deleteIndex(String index, String type, String id) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            DeleteResponse response = client.prepareDelete(index, type, id)
                    .execute()
                    .actionGet();
            return response.isFound();
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    /**
     * 删除多个文档
     * @param index
     * @param type
     * @param ids 多个id逗号隔开
     */
    public boolean deleteIndexs(String index, String type, String ids) throws Exception {
        Client client=null;
        try{
            client=esDataSource.getClient();
            String[] ss=ids.split(",");
            BulkRequestBuilder brb=client.prepareBulk();
            for(String id:ss){
                brb.add(client.prepareDelete(index, type, id));
            }
            BulkResponse br=brb.execute().actionGet();
            if(br.hasFailures()){
                return false;
            }
            return true;
        }finally {
            if(client!=null){
                esDataSource.releaseClient(client);
            }
        }
    }

    public static void indexSettingGet() throws Exception {
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;
        Client client=bs.getEsDataSource().getClient();


        GetSettingsResponse response = client.admin().indices()
                .prepareGetSettings("index-fs-metadata").get();
        for (ObjectObjectCursor<String, Settings> cursor : response.getIndexToSettings()) {
            String index = cursor.key;
            Settings settings = cursor.value;
            Integer shards = settings.getAsInt("index.number_of_shards", null);
            Integer replicas = settings.getAsInt("index.number_of_replicas", null);
            System.out.println(shards);
            System.out.println(replicas);
        }


    }

    public static void mappingAdmin() throws Exception {
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;
        Client client=bs.getEsDataSource().getClient();


        XContentBuilder builder = XContentFactory
                .jsonBuilder()
                .startObject()
//                    .startObject("TJ_BILL_STATISTICS")
//                    .startObject("properties")


                .startObject("relateName")
                .field("type", "string")
                .field("store", "yes")
                        //.field("analyzer","ik")
                .field("index", "not_analyzed")
                .endObject()

//                    .endObject()
//                    .endObject()
                .endObject();

        client.admin().indices().prepareCreate("index-test-lcy").addMapping("type-test-lcy",builder).get();
        //client.admin().indices().prepareUpdateSettings("index-fs-metadata").execute().actionGet();
    }

    public static void clusterAdmin() throws Exception {
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;
        Client client=bs.getEsDataSource().getClient();



        ClusterHealthResponse healths = client.admin().cluster().prepareHealth().get();
        String clusterName = healths.getClusterName();
        System.out.println("clusterName:"+clusterName);
        int numberOfDataNodes = healths.getNumberOfDataNodes();
        System.out.println("numberOfDataNodes:"+numberOfDataNodes);
        int numberOfNodes = healths.getNumberOfNodes();
        System.out.println("numberOfNodes:"+numberOfNodes);

        for (ClusterIndexHealth health : healths.getIndices().values()) {
            String index = health.getIndex();
            System.out.println("numberOfShards:"+index);
            int numberOfShards = health.getNumberOfShards();
            System.out.println("numberOfShards:"+numberOfShards);
            int numberOfReplicas = health.getNumberOfReplicas();
            System.out.println("numberOfReplicas:"+numberOfReplicas);
            ClusterHealthStatus status = health.getStatus();
            System.out.println("clusterHealthStatus:"+status.name());
        }
    }


    public static void indexAdmin()throws Exception{
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;
        Client client=bs.getEsDataSource().getClient();

        //client.admin().indices().prepareCreate(index).execute().actionGet();
        String index="index-fs-metadata";
        XContentBuilder builder = null;
        if(index.equals("index-fs-metadata")){
            builder = XContentFactory
                    .jsonBuilder()
                    .startObject()
                    .startObject("TJ_BILL_STATISTICS")
                    .startObject("properties")


                    .startObject("relateName")
                    .field("type", "string")
                    .field("store", "yes")
                            //.field("analyzer","ik")
                    .field("index", "not_analyzed")
                    .endObject()

//                    .startObject("company")
//                    .field("type", "string")
//                    .field("store", "yes")
//                    .field("analyzer","ik")
//                    .field("index","not_analyzed")
//                    .endObject()
//
//                    .startObject("province")
//                    .field("type", "string")
//                    .field("store", "yes")
//                    .field("analyzer","ik")
//                    .field("index","not_analyzed")
//                    .endObject()

                    .endObject()
                    .endObject()
                    .endObject();
            PutMappingRequest mapping = Requests.putMappingRequest(index).type("TJ_BILL_STATISTICS").source(builder);
            PutMappingResponse pmp=client.admin().indices().putMapping(mapping).actionGet();
            System.out.println(pmp.toString());
        }
    }



    public static String[] getDateRamdom() throws ParseException {
        Random random1 = new Random();
        int month=random1.nextInt(12) + 1;
        //System.out.println("========="+month);

        int monthRange=0;
        if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){
            monthRange=31;
        }else if(month==1){
            monthRange=28;
        }else if(month==4||month==6||month==9||month==11){
            monthRange=30;
        }else{
            monthRange=30;
        }

        Random random = new Random();
        int i=random.nextInt(monthRange) + 1;
        String monthStr=month+"";
        if(month<10){
            monthStr="0"+month+"";
        }
        String dayStr=i+"";
        if(i<10){
            dayStr="0"+i+"";
        }
        String[] times=new String[4];
        String tmpDate="2015-"+monthStr+"-"+dayStr;
        times[0]=tmpDate;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(tmpDate));

        //算检验时间
        cal.add(Calendar.DAY_OF_MONTH, 3);
        int tmpy=cal.get(Calendar.YEAR);
        int tmpm=cal.get(Calendar.MONTH)+1;
        int tmpd=cal.get(Calendar.DAY_OF_MONTH);
        monthStr=tmpm+"";
        if(tmpm<10){
            monthStr="0"+tmpm+"";
        }
        dayStr=tmpd+"";
        if(tmpd<10){
            dayStr="0"+tmpd+"";
        }
        tmpDate=tmpy+"-"+monthStr+"-"+dayStr;
        times[1]=tmpDate;
        //算结算时间
        cal.add(Calendar.DAY_OF_MONTH, 17);
        tmpy=cal.get(Calendar.YEAR);
        tmpm=cal.get(Calendar.MONTH)+1;
        tmpd=cal.get(Calendar.DAY_OF_MONTH);
        monthStr=tmpm+"";
        if(tmpm<10){
            monthStr="0"+tmpm+"";
        }
        dayStr=tmpd+"";
        if(tmpd<10){
            dayStr="0"+tmpd+"";
        }
        tmpDate=tmpy+"-"+monthStr+"-"+dayStr;
        times[2]=tmpDate;
        //算付款时间
        cal.add(Calendar.DAY_OF_MONTH, 25);
        tmpy=cal.get(Calendar.YEAR);
        tmpm=cal.get(Calendar.MONTH)+1;
        tmpd=cal.get(Calendar.DAY_OF_MONTH);
        monthStr=tmpm+"";
        if(tmpm<10){
            monthStr="0"+tmpm+"";
        }
        dayStr=tmpd+"";
        if(tmpd<10){
            dayStr="0"+tmpd+"";
        }
        tmpDate=tmpy+"-"+monthStr+"-"+dayStr;
        times[3]=tmpDate;
        return times;
    }

    public static  void testStatic() throws Exception{
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;


        Client client=bs.getEsDataSource().getClient();
        BoolQueryBuilder bq= QueryBuilders.boolQuery();
        bq.must(QueryBuilders.termQuery("projectId", "DId1"));
        String times="2015-01-01 00:00~2015-07-24 00:00";
        long[] l= TimeUtil.handleTimes(times);
        if(l!=null&&l.length>0){
            bq.must(QueryBuilders.rangeQuery("time").from(l[0]).to(l[1]));
        }
        QueryBuilder queryBuilder = bq;


        SearchRequestBuilder srb = client.prepareSearch("index-tj-finance")
                .setTypes("type-tj-finance-main")
                        //按时间降序号
                        // .addSort("time", SortOrder.DESC)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                        // 设置查询数据的位置,分页用
                        //.setFrom(0)
                        // 设置查询结果集的最大条数
                        //.setSize(500)
                        // 设置是否按查询匹配度排序
                .setExplain(true);
        // 最后就是返回搜索响应信息
        srb.setQuery(bq);
        srb.addAggregation(AggregationBuilders.stats("jb").field("jsBill"));
        long s=System.currentTimeMillis();
        SearchResponse response =srb.execute().actionGet();
        long e=System.currentTimeMillis();
        System.out.println("执行时间:"+(e-s));
        System.out.println(response.toString());
    }

    public static  void testTopic(String mqType) throws Exception{
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;


        Client client=bs.getEsDataSource().getClient();
        SearchResponse sr = null;
        List<Terms.Bucket> list = null;
        List<SysTreeNode> sts = new ArrayList<SysTreeNode>();
        SearchRequestBuilder srb = client.prepareSearch(Contants.INDEX_METADATA);
        if ("all".equals(mqType)){
            srb.setTypes(Contants.TYPE_METADATA_KAFKAMQ,Contants.TYPE_METADATA_REDISMQ);
        } else if ("kafka".equals(mqType)){
            srb.setTypes(Contants.TYPE_METADATA_KAFKAMQ);
        } else if ("redis".equals(mqType)){
            srb.setTypes(Contants.TYPE_METADATA_REDISMQ);
        }
        srb.setQuery(QueryBuilders.matchAllQuery());
        srb.addAggregation(AggregationBuilders.terms("agg1").field("mqTopic"));
        sr = srb.execute().actionGet();
        Terms agg1 = sr.getAggregations().get("agg1");
        list = agg1.getBuckets();
        int i = 1;
        Object key = null;
        String text = null;
        for (Terms.Bucket b : list) {
            SysTreeNode st = new SysTreeNode();
            //st.setId(id + "-" + i);
            key = b.getKey();
            text = key.toString();
            System.out.println("key="+key);
            //System.out.println("text="+text);
            i++;
        }
    }

    /**
     * 财务销售统计
     * @throws Exception
     */
    public static  void testBillSta1() throws Exception{
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;


        String s="2016-09-02 14:40:40";
        String e="2016-09-02 15:18:21";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1=sdf.parse(s);
        Date d2=sdf.parse(e);
        long s1=d1.getTime();
        long s2=d2.getTime();

        s="2016-09-02 15:19:21";
        e="2016-09-02 16:15:10";
        d1=sdf.parse(s);
        d2=sdf.parse(e);
        long s3=d1.getTime();
        long s4=d2.getTime();


        Client client=bs.getEsDataSource().getClient();
        SearchResponse sr = null;
        SearchRequestBuilder srb = client.prepareSearch(Contants.INDEX_METADATA);
        srb.setTypes("type-tj-bill-statistics");
        srb.addAggregation(AggregationBuilders.terms("channel").field("channelName").size(500).
                subAggregation(AggregationBuilders.terms("province").field("regionProvince").size(500)
                        .subAggregation(AggregationBuilders.dateRange("cp-time").field("billTime").addRange(s1, s2).addRange(s3, s4)
                                .subAggregation(AggregationBuilders.sum("cp-sum").field("price")))));
        srb.addAggregation(AggregationBuilders.dateRange("all-agg-time").field("billTime").addRange(s1,s2).addRange(s3, s4)
                .subAggregation(AggregationBuilders.sum("all-agg-sum").field("price")));
        srb.addAggregation(AggregationBuilders.terms("channel-only").field("channelId").size(500)
                .subAggregation(AggregationBuilders.dateRange("channel-only-time").field("billTime").addRange(s1, s2).addRange(s3, s4)
                        .subAggregation(AggregationBuilders.sum("channel-only-sum").field("price"))));
        srb.setSize(0);
        sr = srb.execute().actionGet();
        System.out.println(sr.toString());
    }

    /**
     * 财务销售统计
     * @throws Exception
     */
    public static  void testBillSta2() throws Exception{
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;


        String s="2016-09-02 14:40:40";
        String e="2016-09-02 15:18:21";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1=sdf.parse(s);
        Date d2=sdf.parse(e);
        long s1=d1.getTime();
        long s2=d2.getTime();

        s="2016-09-02 15:19:21";
        e="2016-09-02 16:15:10";
        d1=sdf.parse(s);
        d2=sdf.parse(e);
        long s3=d1.getTime();
        long s4=d2.getTime();


        Client client=bs.getEsDataSource().getClient();
        SearchResponse sr = null;
        SearchRequestBuilder srb = client.prepareSearch(Contants.INDEX_METADATA);
        srb.setTypes("type-tj-bill-statistics");
        srb.addAggregation(AggregationBuilders.terms("relate").field("relateName").size(500)
                .subAggregation(AggregationBuilders.dateRange("relate-time").field("billTime").addRange(s1, s2).addRange(s3, s4)
                        .subAggregation(AggregationBuilders.sum("relate-sum").field("price"))));
        srb.addAggregation(AggregationBuilders.dateRange("all-agg-time").field("billTime").addRange(s1, s2).addRange(s3, s4)
                .subAggregation(AggregationBuilders.sum("all-agg-sum").field("price")));
        srb.setSize(0);

        sr = srb.execute().actionGet();
        System.out.println(sr.toString());
    }

    public static void getTest() throws Exception {

        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;
        Client client=bs.getEsDataSource().getClient();
        Map msp=client.prepareGet("index-fs-metadata","TJ_BILL_STATISTICS","relateName").execute().actionGet().getSource();
        int i=0;
    }


    public static void testPutMetadataMapping() throws Exception {
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;

        Client client=bs.getEsDataSource().getClient();

        client.admin().indices().preparePutMapping("index-fs-metadata")
                .setType("type-tj-bill-statistics")
                .setSource("{\n" +
                        "  \"properties\": {\n" +

                        "    \"channelName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"belongChannelName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"laboratoryName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"regionProvinceName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"regionCityName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"regionAreaName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"memberName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"relateName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"relateName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"sysName\": {\n" +
                        "      \"type\": \"string\"\n" + "," +
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"l1Name\": {\n" +
                        "      \"type\": \"string\"\n" + "," +
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"l2Name\": {\n" +
                        "      \"type\": \"string\"\n" + "," +
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"l3Name\": {\n" +
                        "      \"type\": \"string\"\n" + "," +
                        "      \"index\": \"not_analyzed\"\n" +
                        "    }\n" +

                        "  }\n" +
                        "}")
                .get();
    }







    public static void createIndex() throws Exception {
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;

        Client client=bs.getEsDataSource().getClient();

        client.admin().indices().prepareCreate("index-fs-metadata")
                .setSettings(Settings.builder()
                                .put("index.number_of_shards", 3)
                                .put("index.number_of_replicas", 1)
                )
                .get();
    }



    public static void operEs(){
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
//        es.clusterName="elasticsearch-cluster-fs";
//        es.ips="10.160.64.209:9300,10.25.172.120:9301,10.26.248.235:9302,10.25.6.128:9303";
        es.clusterName="elasticsearch-test";
        es.ips="10.117.215.193:9300,10.117.69.202:9301";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;

        try {
            Client client=bs.getEsDataSource().getClient();
            ObjectMapper mapper = new ObjectMapper();
            Sys sys=new Sys();
            String id="id-test-006";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("sys-test-006");
            sys.setDesc("desc-test-006");
            String json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化es
     */
    public static void initEsDb(){
        try{
            ElasticsearchDataSource es=new ElasticsearchDataSource();
            es.maxActive=30;
            es.maxIdle=20;
            es.minIdle=1;
            es.maxWait=100;
//            es.clusterName="elasticsearch-cluster-fs";
//            es.ips="10.160.64.209:9300,10.25.172.120:9301,10.26.248.235:9302,10.25.6.128:9303";
            es.clusterName="elasticsearch-test";
            es.ips="10.117.215.193:9300,10.117.69.202:9301";
            BaseElasticsearch bs=new BaseElasticsearch();
            bs.esDataSource=es;

            Client client=bs.getEsDataSource().getClient();

            /*//create metadataindex
            client.admin().indices().prepareCreate("index-fs-metadata")
                    .setSettings(Settings.builder()
                                    .put("index.number_of_shards",6)
                                    .put("index.number_of_replicas",1)
                    )
                    .get();

            //set mapping
            client.admin().indices().preparePutMapping("index-fs-metadata")
                    .setType("type-fs-metadata-log")
                    .setSource("{\n" +
                            "  \"properties\": {\n" +

                            "    \"sysName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l1Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l2Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l3Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    }\n" +



                            "  }\n" +
                            "}")
                    .get();*/

            //insert user data
            User u=new User();
            u.setId("user_id_002");
            u.setTime(new Date());
            u.setUpdateTime(new Date());
            u.setUserName("xxxx");
            u.setUserPassword("e10adc3949ba59abbe56e057f20f883e");
            ObjectMapper mapper = new ObjectMapper();
            String json=mapper.writeValueAsString(u);

            IndexResponse response = client.prepareIndex("index-fs-parameter", "type-fs-parameter-user").setId("user_id_002").setSource(json).execute().actionGet();

            //insert sys data
            /*Sys sys=new Sys();
            String id="20fc0c39866a4789aa26bb23d6ed9d7a";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("fsview");
            sys.setDesc("服务管理平台");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();

            sys=new Sys();
            id="81c8cc4d318144558d25be30984f6114";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("tj");
            sys.setDesc("体检系统");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();

            sys=new Sys();
            id="adef855356ba4dddb997a4e16c846b92";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("box");
            sys.setDesc("仪器盒子");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();

            sys=new Sys();
            id="7ffe65b4dc7a489db23c32a4d7b7d2cf";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("ins");
            sys.setDesc("仪器平台");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();

            sys=new Sys();
            id="54e08d066a894a96be9f75854a72e5ca";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("fs");
            sys.setDesc("云基服务");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();

            sys=new Sys();
            id="8f1b37d5aa8b45699ef0d46473d1de44";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("netty");
            sys.setDesc("通信服务模块");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();

*/
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

        /**
         * 初始化tj es
         */
    public static void initTjEsDb(){
        try{
            ElasticsearchDataSource es=new ElasticsearchDataSource();
            es.maxActive=30;
            es.maxIdle=20;
            es.minIdle=1;
            es.maxWait=100;
//            es.clusterName="elasticsearch-cluster-fs";
//            es.ips="10.160.64.209:9300,10.25.172.120:9301,10.26.248.235:9302,10.25.6.128:9303";
            es.clusterName="elasticsearch-test";
            es.ips="10.117.215.193:9300,10.117.69.202:9301";
            BaseElasticsearch bs=new BaseElasticsearch();
            bs.esDataSource=es;

            Client client=bs.getEsDataSource().getClient();

            //create metadataindex
            client.admin().indices().prepareCreate("index-tj-metadata")
                    .setSettings(Settings.builder()
                                    .put("index.number_of_shards",6)
                                    .put("index.number_of_replicas",1)
                    )
                    .get();

            //set mapping
            client.admin().indices().preparePutMapping("index-tj-metadata")
                    .setType("type-tj-bill-statistics")
                    .setSource("{\n" +
                            "  \"properties\": {\n" +

                            "    \"sysName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l1Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l2Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l3Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"channelName\": {\n" +
                            "      \"type\": \"string\"\n" +","+
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"belongChannelName\": {\n" +
                            "      \"type\": \"string\"\n" +","+
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"laboratoryName\": {\n" +
                            "      \"type\": \"string\"\n" +","+
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"regionProvinceName\": {\n" +
                            "      \"type\": \"string\"\n" +","+
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"regionCityName\": {\n" +
                            "      \"type\": \"string\"\n" +","+
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"regionAreaName\": {\n" +
                            "      \"type\": \"string\"\n" +","+
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"memberName\": {\n" +
                            "      \"type\": \"string\"\n" +","+
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"relateName\": {\n" +
                            "      \"type\": \"string\"\n" +","+
                            "      \"index\": \"not_analyzed\"\n" +
                            "    }\n" +

                            "  }\n" +
                            "}")
                    .get();
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }


    /**
     * 初始化nip es
     */
    public static void initNipEsDb(){
        try{
            ElasticsearchDataSource es=new ElasticsearchDataSource();
            es.maxActive=30;
            es.maxIdle=20;
            es.minIdle=1;
            es.maxWait=100;
//            es.clusterName="elasticsearch-cluster-fs";
//            es.ips="10.160.64.209:9300,10.25.172.120:9301,10.26.248.235:9302,10.25.6.128:9303";
            es.clusterName="elasticsearch-test";
            es.ips="10.117.215.193:9300,10.117.69.202:9301";
            BaseElasticsearch bs=new BaseElasticsearch();
            bs.esDataSource=es;

            Client client=bs.getEsDataSource().getClient();

            //create metadataindex
//            client.admin().indices().prepareCreate("index-tj-metadata")
//                    .setSettings(Settings.builder()
//                                    .put("index.number_of_shards",6)
//                                    .put("index.number_of_replicas",1)
//                    )
//                    .get();

            //set mapping
            client.admin().indices().preparePutMapping("index-nip-process")
                    .setType("type-nip-process")
                    .setSource("{\n" +
                            "  \"properties\": {\n" +

                            "    \"sysName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l1Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l2Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l3Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"inputLaboratoryName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"laboratoryName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"deptName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"testItemName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"groupTestItemName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"result\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"cusName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"specimenStatusName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"remark\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"dcName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    }\n" +



                            "  }\n" +
                            "}")
                    .get();


            client.admin().indices().preparePutMapping("index-nip-exception")
                    .setType("type-nip-exception")
                    .setSource("{\n" +
                            "  \"properties\": {\n" +

                            "    \"sysName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l1Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l2Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l3Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"exceptionType\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"customerName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"testItemName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"laboratoryName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"deptName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    }\n" +


                            "  }\n" +
                            "}")
                    .get();
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }

    /**
     * 财务销售统计
     * @throws Exception
     */
    public static  void testBillSta4() throws Exception{
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;


        String s="2016-09-02 14:40:40";
        String e="2016-09-02 15:18:21";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1=sdf.parse(s);
        Date d2=sdf.parse(e);
        long s1=d1.getTime();
        long s2=d2.getTime();

        s="2016-09-02 15:19:21";
        e="2016-09-02 16:15:10";
        d1=sdf.parse(s);
        d2=sdf.parse(e);
        long s3=d1.getTime();
        long s4=d2.getTime();


        Client client=bs.getEsDataSource().getClient();
        SearchResponse sr = null;
        SearchRequestBuilder srb = client.prepareSearch(Contants.INDEX_METADATA);
        srb.setTypes("type-tj-bill-statistics");
        srb.addAggregation(AggregationBuilders.terms("channel").field("channelName").size(500).
                subAggregation(AggregationBuilders.terms("province").field("regionProvince").size(500)
                        .subAggregation(AggregationBuilders.dateRange("cp-time").field("billTime").addRange(s1, s2).addRange(s3, s4)
                                .subAggregation(AggregationBuilders.sum("cp-sum").field("price")))));
        srb.addAggregation(AggregationBuilders.dateRange("all-agg-time").field("billTime").addRange(s1,s2).addRange(s3, s4)
                .subAggregation(AggregationBuilders.sum("all-agg-sum").field("price")));
        srb.addAggregation(AggregationBuilders.terms("channel-only").field("channelId").size(500)
                .subAggregation(AggregationBuilders.dateRange("channel-only-time").field("billTime").addRange(s1, s2).addRange(s3, s4)
                        .subAggregation(AggregationBuilders.sum("channel-only-sum").field("price"))));
        srb.setSize(0);
        sr = srb.execute().actionGet();
        System.out.println(sr.toString());
    }

    /**
     * 财务销售统计
     * @throws Exception
     */
    public static  void testBillSta5() throws Exception{
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;


        String s="2016-09-02 14:40:40";
        String e="2016-09-02 15:18:21";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1=sdf.parse(s);
        Date d2=sdf.parse(e);
        long s1=d1.getTime();
        long s2=d2.getTime();

        s="2016-09-02 15:19:21";
        e="2016-09-02 16:15:10";
        d1=sdf.parse(s);
        d2=sdf.parse(e);
        long s3=d1.getTime();
        long s4=d2.getTime();


        Client client=bs.getEsDataSource().getClient();
        SearchResponse sr = null;
        SearchRequestBuilder srb = client.prepareSearch(Contants.INDEX_METADATA);
        srb.setTypes("type-tj-bill-statistics");
        srb.addAggregation(AggregationBuilders.terms("relate").field("relateName").size(500)
                .subAggregation(AggregationBuilders.dateRange("relate-time").field("billTime").addRange(s1, s2).addRange(s3, s4)
                        .subAggregation(AggregationBuilders.sum("relate-sum").field("price"))));
        srb.addAggregation(AggregationBuilders.dateRange("all-agg-time").field("billTime").addRange(s1, s2).addRange(s3, s4)
                .subAggregation(AggregationBuilders.sum("all-agg-sum").field("price")));
        srb.setSize(0);

        sr = srb.execute().actionGet();
        System.out.println(sr.toString());
    }

    public static void getTest1() throws Exception {

        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;
        Client client=bs.getEsDataSource().getClient();
        Map msp=client.prepareGet("index-fs-metadata","TJ_BILL_STATISTICS","relateName").execute().actionGet().getSource();
        int i=0;
    }


    public static void testPutMetadataMapping2() throws Exception {
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;

        Client client=bs.getEsDataSource().getClient();

        client.admin().indices().preparePutMapping("index-fs-metadata")
                .setType("type-tj-bill-statistics")
                .setSource("{\n" +
                        "  \"properties\": {\n" +

                        "    \"channelName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"belongChannelName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"laboratoryName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"regionProvinceName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"regionCityName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"regionAreaName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"memberName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"relateName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"relateName\": {\n" +
                        "      \"type\": \"string\"\n" +","+
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"sysName\": {\n" +
                        "      \"type\": \"string\"\n" + "," +
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"l1Name\": {\n" +
                        "      \"type\": \"string\"\n" + "," +
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"l2Name\": {\n" +
                        "      \"type\": \"string\"\n" + "," +
                        "      \"index\": \"not_analyzed\"\n" +
                        "    },\n" +

                        "    \"l3Name\": {\n" +
                        "      \"type\": \"string\"\n" + "," +
                        "      \"index\": \"not_analyzed\"\n" +
                        "    }\n" +

                        "  }\n" +
                        "}")
                .get();
    }







    public static void createIndex1() throws Exception {
        ElasticsearchDataSource es=new ElasticsearchDataSource();
        es.maxActive=30;
        es.maxIdle=20;
        es.minIdle=1;
        es.maxWait=100;
        es.clusterName="elasticsearch";
        es.ips="120.26.54.243:9300";
        BaseElasticsearch bs=new BaseElasticsearch();
        bs.esDataSource=es;

        Client client=bs.getEsDataSource().getClient();

        client.admin().indices().prepareCreate("index-fs-metadata")
                .setSettings(Settings.builder()
                        .put("index.number_of_shards", 3)
                        .put("index.number_of_replicas", 1)
                )
                .get();
    }

    /**
     * 初始化es
     */
    public static void initEsDb1(){
        try{
            ElasticsearchDataSource es=new ElasticsearchDataSource();
            es.maxActive=30;
            es.maxIdle=20;
            es.minIdle=1;
            es.maxWait=100;
            es.clusterName="elasticsearch-cluster-fs";
            es.ips="10.160.64.209:9300,10.25.172.120:9301,10.26.248.235:9302,10.25.6.128:9303";
            BaseElasticsearch bs=new BaseElasticsearch();
            bs.esDataSource=es;

            Client client=bs.getEsDataSource().getClient();

            //create metadataindex
            client.admin().indices().prepareCreate("index-fs-metadata")
                    .setSettings(Settings.builder()
                            .put("index.number_of_shards",6)
                            .put("index.number_of_replicas",1)
                    )
                    .get();

            //set mapping
            client.admin().indices().preparePutMapping("index-fs-metadata")
                    .setType("type-fs-metadata-log")
                    .setSource("{\n" +
                            "  \"properties\": {\n" +

                            "    \"sysName\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l1Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l2Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    },\n" +

                            "    \"l3Name\": {\n" +
                            "      \"type\": \"string\"\n" + "," +
                            "      \"index\": \"not_analyzed\"\n" +
                            "    }\n" +

                            "  }\n" +
                            "}")
                    .get();

            //insert user data
            User u=new User();
            u.setId("user_id_001");
            u.setTime(new Date());
            u.setUpdateTime(new Date());
            u.setUserName("admin");
            u.setUserPassword("123456");
            ObjectMapper mapper = new ObjectMapper();
            String json=mapper.writeValueAsString(u);

            IndexResponse response = client.prepareIndex("index-fs-parameter", "type-fs-parameter-user").setId("user_id_001").setSource(json).execute().actionGet();

            //insert sys data
            Sys sys=new Sys();
            String id="20fc0c39866a4789aa26bb23d6ed9d7a";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("fsview");
            sys.setDesc("服务管理平台");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();

            sys=new Sys();
            id="81c8cc4d318144558d25be30984f6114";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("tj");
            sys.setDesc("体检系统");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();

            sys=new Sys();
            id="adef855356ba4dddb997a4e16c846b92";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("box");
            sys.setDesc("仪器盒子");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();

            sys=new Sys();
            id="7ffe65b4dc7a489db23c32a4d7b7d2cf";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("ins");
            sys.setDesc("仪器平台");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();

            sys=new Sys();
            id="54e08d066a894a96be9f75854a72e5ca";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("fs");
            sys.setDesc("云基服务");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();

            sys=new Sys();
            id="8f1b37d5aa8b45699ef0d46473d1de44";
            sys.setId(id);
            sys.setTime(new Date());
            sys.setUpdateTime(new Date());
            sys.setSysName("netty");
            sys.setDesc("通信服务模块");
            json=mapper.writeValueAsString(sys);
            client.prepareIndex("index-fs-parameter", "type-fs-parameter-system").setId(id).setSource(json).execute().actionGet();


        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }

    public static void main(String[] args) throws Exception {
        try{
            initNipEsDb();
            //operEs();
            //testStatic();
            //testTopic("all");
            //testBillSta1();
            //testBillSta2();
            //indexAdmin();
            //indexSettingGet();
            //clusterAdmin();
            //mappingAdmin();
            //getTest();
//          //createIndex();
//          //testPutMetadataMapping();
            //initEsDb();
            //initTjEsDb();
            ////////////////////////////////////////////////////////////
            // 修改密码
            //Map<String,String> map = new HashMap<String, String>();
            //map.put("userPassword","e10adc3949ba59abbe56e057f20f883e");

//            ElasticsearchDataSource es=new ElasticsearchDataSource();
//            es.maxActive=30;
//            es.maxIdle=20;
//            es.minIdle=1;
//            es.maxWait=100;
//            //es.clusterName="elasticsearch-cluster-fs";
//            //es.ips="10.160.64.209:9300,10.25.172.120:9301,10.26.248.235:9302,10.25.6.128:9303";
//            es.clusterName="elasticsearch-test";
//            es.ips="10.117.215.193:9300,10.117.69.202:9301";
//            BaseElasticsearch bs=new BaseElasticsearch();
//            bs.esDataSource=es;
//            // "index-fs-parameter", "type-fs-parameter-user").setId("user_id_001")
//            //bs.updateIndex("index-fs-parameter","type-fs-parameter-user","user_id_001",map);
//            String str = "{\"fileType\":\"netty\",\"l3Name\":\"DEF\",\"host\":\"10.26.249.70\",\"seqNo\":\"1\",\"l2Name\":\"DEF\",\"showTime\":\"2016-09-19 03:10:10\",\"requestType\":\"insert\",\"retransmissionTime\":\"2016-09-19 03:10:10\",\"code\":\"N_YQ_TES_RPFB\",\"sysName\":\"netty\",\"ext\":\"json\",\"fileSize\":1.0,\"id\":\"37ec22694aac4948b54df54865e545dc\",\"l1Name\":\"DEF\",\"requestSize\":0.6,\"time\":1474225810672,\"sysId\":\"8f1b37d5aa8b45699ef0d46473d1de44\",\"month\":9,\"dfsId\":\"group2/M00/00/4D/Chpn8Ffe5pKATGrfAAAEyMUEg3A42.json\",\"year\":2016,\"day\":19,\"retransmissionCount\":0,\"deviceId\":\"26e7a916547a4d91b146a4f29d41b0ac\"}";
//            //bs.createIndex("index-fs-metadata","type-fs-metadata-fastdfs",str);
//            bs.createIndexById("index-fs-metadata","type-fs-metadata-fastdfs",str,"37ec22694aac4948b54df54865e545dc");
            //////////////////////////////////////////////////////////////////////////////////
            //testTopic("all");
            //testBillSta1();
            //testBillSta2();
            //indexAdmin();
            //indexSettingGet();
            //clusterAdmin();
            //mappingAdmin();
            //getTest();
//          //createIndex();
//          //testPutMetadataMapping();
            initEsDb();
            // 更新密码
            Map<String,String> map = new HashMap<String, String>();
            map.put("userPassword","e10adc3949ba59abbe56e057f20f883e");
            BaseElasticsearch bs = new BaseElasticsearch();
            // "index-fs-parameter", "type-fs-parameter-user").setId("user_id_001")
            bs.updateIndex("index-fs-parameter","type-fs-parameter-user","user_id_001",map);
        }catch ( Exception ex){
            ex.printStackTrace();
        }
    }
}
